package com.emm.yixun.marketing.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.BaseCodeValueService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.PriceSchemeDetailService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.RetainService;
import com.emm.yixun.basic.service.RoomChangeHistoryService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.PriceSchemeDetail;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.Retain;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BaseCodeValueDto;
import com.emm.yixun.common.model.dto.ProjectRoomDto;
import com.emm.yixun.common.model.dto.RetainDetailView;
import com.emm.yixun.common.model.dto.RetainDto;
import com.emm.yixun.common.model.dto.RoomChangeHistoryDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.marketing.service.RetainServiceFacade;

@Service("retainServiceFacade")
@WebService(name = "com.emm.yixun.marketing.service.RetainServiceFacade")
public class RetainServiceFacadeImpl implements RetainServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private RetainService service;

	@Autowired
	private RoomChangeHistoryService roomChangeHistoryService;

	@Autowired
	private ProjectRoomService projectRoomService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private UserService userService;

	@Autowired
	private PriceSchemeDetailService priceSchemeDetailService;
	@Autowired
	private DataPermissionService dataPermissionService;

	@Autowired
	private BaseCodeValueService baseCodeValueService;

	@Override
	public Response<RetainDto> save(RetainDto dto, User user) {
		Response<RetainDto> response = new Response<RetainDto>();
		ProjectRoom room = projectRoomService.selectById(dto.getRoomId());
		try {
			dto.setAgentId(user.getId());
			dto.setRetainDate(new Date());
			dto.setMerchantId(user.getMerchantId());
			dto.setAccessCode(room.getProjectCode());
			dto.setUserCode(user.getUserCode());
			dto.setCreateUserId(user.getId());
			dto.setCreateTime(new Date());
			dto.setDelFlag("0");
			dto.setUpdateTime(new Date());
			RetainDto mDto = service.create(dto);
			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			} else {
				// 新增房间的变更记录
				RoomChangeHistoryDto hisdto = new RoomChangeHistoryDto();
				hisdto.setRoomId(dto.getRoomId());
				hisdto.setBusinessDynamics(RoomStatusEnum.RETAIN.getDes());
				hisdto.setRemark("房态由【" + RoomStatusEnum.getByNo(room.getRoomStatus()).getDes() + "】转为【"
						+ RoomStatusEnum.RETAIN.getDes() + "】");
				hisdto.setMerchantId(user.getMerchantId());
				hisdto.setAccessCode(room.getProjectCode());
				hisdto.setUserCode(user.getUserCode());
				hisdto.setCreateUserId(user.getId());
				hisdto.setCreateTime(new Date());
				hisdto.setDelFlag("0");
				hisdto.setBusinessHref("/marketing/retain/retainDetail?id=" + mDto.getId());
				roomChangeHistoryService.create(hisdto);
				// 更改房间状态为保留
				ProjectRoomDto roomEntity = new ProjectRoomDto();
				roomEntity.setId(room.getId());
				roomEntity.setRoomStatus(RoomStatusEnum.RETAIN.getNo());
				projectRoomService.update(roomEntity);
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(RetainDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = service.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			RetainDto mDto = new RetainDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Retain> findById(Long id) {
		Response<Retain> response = new Response<Retain>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			Retain entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<Retain> findByDto(RetainDto dto) {
		ResponseList<Retain> response = new ResponseList<Retain>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<Retain> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<Retain> findPageByDto(RetainDto dto, Integer begin, Integer row) {
		Page<Retain> response = new Page<Retain>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<Retain> page = service.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.emm.yixun.marketing.service.RetainServiceFacade#getRetainDtoList(com.emm.
	 * yixun.common.model.dto.RetainDto, java.lang.Integer, java.lang.Integer)
	 */
	@Override
	public Response<Page<RetainDto>> getRetainDtoList(RetainDto reqDto, Integer pageSize, Integer pageNum) {
		Response<Page<RetainDto>> resDto = new Response<Page<RetainDto>>();
		try {

			// 数据权限
			if (SysConstants.openDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(reqDto.getPermissionUserId(),
						reqDto.getResourcesCode(), reqDto.getPrefix(), reqDto.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					resDto.setResultMessage(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					resDto.setSuccess(false);
					return resDto;
				}
				reqDto.setDataPermission(dataPermissionArr[1]);
			}

			Page<RetainDto> page = service.getPageDtoModel(reqDto, PageUtil.begin(pageNum, pageSize), pageSize);
			page.setPageSize(pageSize);
			resDto.setSuccess(true);
			resDto.setEntity(page);
			return resDto;
		} catch (Exception e) {
			logger.error("查询分页数据错误：{}", e);
			resDto.setSuccess(false);
			return resDto;
		}
	}

	@Override
	public RetainDetailView findRetainDetailById(Long id) {
		try {
			RetainDetailView rdv = new RetainDetailView();
			// 保留信息
			Retain retain = service.selectById(id);
			if (retain != null) {
				rdv = BeanUtil.convert2T(rdv, retain);
				User user = userService.selectById(rdv.getAgentId());
				rdv.setAgentCN(user.getUserName());
				// 客户信息

				Customer customer = customerService.selectById(retain.getCustomerId());
				if (customer != null) {
					BaseCodeValueDto bcvDto = new BaseCodeValueDto();
					bcvDto.setMerchantId(customer.getMerchantId());
					List<BaseCodeValue> bcvList = baseCodeValueService.selectListFilterDelFlag(bcvDto);
					Map<Long, String> bcvMap = new HashMap<Long, String>();
					for (BaseCodeValue bcv : bcvList) {
						bcvMap.put(bcv.getId(), bcv.getCodeName());
					}

					rdv = BeanUtil.convert2T(rdv, customer);
					if (null != rdv.getPeDocumentType()) {
						rdv.setPeDocumentType(bcvMap.get(Long.parseLong(rdv.getPeDocumentType())));
					}
					// 客户来源
					if (null != rdv.getCustomerOrigin()) {
						rdv.setCustomerOrigin(bcvMap.get(Long.parseLong(rdv.getCustomerOrigin())));
					}
				}

				// 房产信息
				rdv = getProjectRoomInfo(rdv, retain.getRoomId());

				User updateName = userService.selectById(retain.getUpdateUserId());
				if (updateName != null) {
					rdv.setUpdateUser(updateName.getUserName());
					rdv.setUpdateDate(retain.getUpdateTime());
					rdv.setRemark(retain.getRemark());
				}
			}

			return rdv;
		} catch (Exception e) {
			logger.error("findRetainDetailById error: ", e);
		}
		return null;
	}

	@Override
	public RetainDetailView getProjectRoomInfo(RetainDetailView rdv, Long id) {
		// 房产信息
		ProjectRoom room = projectRoomService.selectById(id);
		if (room != null) {
			rdv = BeanUtil.convert2T(rdv, room);
			RoomStatusEnum roomStatus = RoomStatusEnum.getByNo(rdv.getRoomStatus());
			if (roomStatus != null) {
				rdv.setRoomStatus(roomStatus.getDes());
			}
			PriceSchemeDetail detail = priceSchemeDetailService.selectEntityByRoomId(room.getId());
			if (detail != null && detail.getId() != null) {
				rdv.setUnitPrice(detail.getUnitPrice());
				rdv.setTotalPrice(detail.getTotalPrice());
			}
			return rdv;
		}
		return null;
	}

	@Override
	public Response<Boolean> roomStatusRevoke(Long id, User user, String remark) {
		Response<Boolean> response = new Response<Boolean>();
		Retain retain = service.selectById(id);
		try {
			ProjectRoom room = projectRoomService.selectById(retain.getRoomId());
			RetainDto entity = new RetainDto();
			entity.setRetainType("1");
			entity.setRemark(remark);
			entity.setUpdateUserId(user.getId());
			entity.setId(id);
			service.update(entity);
			// 新增变更记录
			RoomChangeHistoryDto hisdto = new RoomChangeHistoryDto();
			hisdto.setRoomId(retain.getRoomId());
			hisdto.setBusinessDynamics("撤销" + RoomStatusEnum.RETAIN.getDes());
			hisdto.setRemark("房态由【" + RoomStatusEnum.getByNo(room.getRoomStatus()).getDes() + "】转为【"
					+ RoomStatusEnum.VENDIBILITY.getDes() + "】");
			hisdto.setMerchantId(user.getMerchantId());
			hisdto.setAccessCode(room.getProjectCode());
			hisdto.setUserCode(user.getUserCode());
			hisdto.setCreateUserId(user.getId());
			hisdto.setCreateTime(new Date());
			hisdto.setDelFlag("0");
			hisdto.setBusinessHref("/marketing/retain/retainDetail?id=" + id);
			roomChangeHistoryService.create(hisdto);
			// 更改房间状态
			ProjectRoomDto roomEntity = new ProjectRoomDto();
			roomEntity.setId(room.getId());
			roomEntity.setRoomStatus(RoomStatusEnum.VENDIBILITY.getNo());
			projectRoomService.update(roomEntity);
			response.setEntity(true);
			return response;
		} catch (Exception e) {
			logger.error("roomStatusRevoke error: ", e);
		}
		return null;
	}

	@Override
	public void taskRun() {
		/*
		 * 1.查询可解除保留记录 2.根据当前商户系统管理员 3.解除保留
		 */
		RetainDto queryDto = new RetainDto();
		// 设置保留类型
		queryDto.setRetainType("0");
		// 设置时间
		queryDto.setEndValidityAfter(
				com.emm.yixun.common.utils.DateUtils.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
		List<Retain> retainList = service.selectListByDto(queryDto);
		if (retainList == null || retainList.size() == 0)
			return;
		Map<Long, User> merchantUserMap = new HashMap<Long, User>();
		for (Retain retain : retainList) {
			Long merchantId = retain.getMerchantId();
			User adminUser = merchantUserMap.get(merchantId);
			if (null == adminUser) {
				UserDto dto = new UserDto();
				dto.setMerchantId(retain.getMerchantId());
				dto.setIsAdmin("1");
				List<User> user = userService.selectListByDto(dto);
				if (user != null && user.size() > 0) {
					adminUser = user.get(0);
					merchantUserMap.put(merchantId, user.get(0));
				}
			}
			if (null == adminUser) {
				continue;
			}
			roomStatusRevoke(retain.getId(), adminUser, "系统任务自动撤销:原因:【当前日期超过保留结束日期】");
		}
	}
}
